﻿namespace ConsoleApp.Tree;

public class TreeNode<T> : IHierarchical<T>
{
    private T _value;
    private List<TreeNode<T>> _children = new List<TreeNode<T>>();
    private TreeNode<T> _parent;
 
    public T Current => _value;
    public IHierarchical<T> Root { get; }
    IHierarchical<T> IHierarchical<T>.Parent => Parent;

    IEnumerable<IHierarchical<T>> IHierarchical<T>.Children => Children;

    public IEnumerable<IHierarchical<T>> Descendants { get; }
    public IReadOnlyList<TreeNode<T>> Children => _children.AsReadOnly();
    public TreeNode<T> Parent => _parent;
    public bool IsLeaf => !_children.Any();
    public bool HasChild => _children.Any();
    public int Level => _parent?.Level + 1 ?? 0;
    public int Height => 1 + _children.Max(c => c.Height);
 
    public TreeNode(T value) => _value = value;
    
    public void AddChild(TreeNode<T> child)
    {
        child._parent = this;
        _children.Add(child);
    }
    
    public void RemoveChild(TreeNode<T> child)
    {
        if (_children.Remove(child))
            child._parent = null;
    }
}